﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleMvvmToolkit;
using System.Windows.Input;
using System.ComponentModel;
using BuyTicket.Service;
using BuyTicket.Models;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using System.Threading;

namespace BuyTicket.ViewModels
{
    class BoardViewModel : ViewModelBase<BoardViewModel>
    {
        Timer m_Timer = null;

        public BoardViewModel()
        {
            if (!IsInDesignMode)
            {
                m_Timer = new Timer(new TimerCallback(TimeCallback),
                    null,
                    0,
                    30 * 1000);
            }
        }

        void TimeCallback(object args)
        {
            if (m_IsAutoRefresh)
            {
                Refresh();
            }
        }

        event EventHandler<NotificationEventArgs> m_Loading;
        public event EventHandler<NotificationEventArgs> Loading
        {
            add
            {
                m_Loading += value;
            }
            remove
            {
                m_Loading -= value;
            }
        }

        event EventHandler<NotificationEventArgs> m_Loaded;
        public event EventHandler<NotificationEventArgs> Loaded
        {
            add
            {
                m_Loaded += value;
            }
            remove
            {
                m_Loaded -= value;
            }
        }

        bool m_IsAutoRefresh = false;
        public bool IsAutoRefresh
        {
            get
            {
                return m_IsAutoRefresh;
            }
            set
            {
                m_IsAutoRefresh = true;
                this.NotifyPropertyChanged(m => m.IsAutoRefresh);
            }
        }

        List<Ticket> m_Tickets = null;
        public List<Ticket> Tickets
        {
            get
            {
                return m_Tickets;
            }
        }

        ICommand m_RefreshCommand = null;
        public ICommand RefreshCommand
        {
            get
            {
                return m_RefreshCommand ?? (m_RefreshCommand = new DelegateCommand(Refresh));
            }
        }

        void Refresh()
        {
            this.Async(new Func<object>(() =>
            {
                List<Ticket> result = new List<Ticket>();
                string strHtml;
                if (BuyTicketServiceV2.GetTickets(out strHtml))
                {
                    //通过strHtml解析出Ticket
                    string[] sArry = Regex.Split(strHtml, @"\\n");
                    foreach (var strLine in sArry)
                    {
                        HtmlDocument document = new HtmlDocument();
                        document.LoadHtml(strLine);
                        var node = document.DocumentNode.SelectSingleNode("//a[@name='btn130_2']");
                        if (node != null)
                        {
                            var attribute = node.Attributes["onclick"];
                            if (attribute != null)
                            {
                                string temp = Utility.SplitString(attribute.Value,
                                    "'",
                                    "'");
                                sArry = Regex.Split(temp, "#");

                                result.Add(new Ticket(sArry[0],
                                    string.Format("{0}/{1}",sArry[7],sArry[2]),
                                    string.Format("{0}/{1}", sArry[8], sArry[6]),
                                    temp));
                            }
                            else
                            {

                            }
                        }
                    }
                }
                return result;
            }), new Action<object>(args =>
            {
                List<Ticket> tickets = args as List<Ticket>;
                if (tickets != null)
                {
                    m_Tickets = tickets;
                    this.NotifyPropertyChanged(m => m.Tickets);
                }
            }));
        }

        void Async(Func<object> func, Action<object> completed)
        {
            using (BackgroundWorker worker = new BackgroundWorker())
            {
                if (m_Loading != null)
                {
                    m_Loading(this, new NotificationEventArgs());
                }
                worker.DoWork += (sender, e) =>
                {
                    e.Result = func();
                };
                worker.RunWorkerCompleted += (sender, e) =>
                {
                    completed(e.Result);
                    if (m_Loaded != null)
                    {
                        m_Loaded(this, new NotificationEventArgs());
                    }
                };
                worker.RunWorkerAsync();
            }
        }

       
    }
}
